﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace sdamarketing
{
    public class RolesAndPrivileges
    {
        public static void addRole(string name)
        {
            DateTime dateTime = DateTime.Now;
            SqlConnection connection = ConnectionMenager.GetConnection();

            string sql = @"INSERT INTO Roles (name, dateCreated) VALUES (@nameP,@dateTimeP)";
            SqlCommand command = new SqlCommand(sql, connection);

            command.Parameters.AddWithValue("@dateTimeP", dateTime);
            command.Parameters.AddWithValue("@nameP", name);

            command.ExecuteNonQuery();
            connection.Close();
        }

        public static void DeleteRowsFromtPanelRoles(int id)
        {
            SqlConnection connection = ConnectionMenager.GetConnection();
            DateTime dateCreated = DateTime.Now;

            string sql = @"Delete from tbr_PanelRoles Where idPanel = @idP";
            SqlCommand command = new SqlCommand(sql, connection);

            command.Parameters.AddWithValue("@idP", id);

            command.ExecuteNonQuery();
            connection.Close();
        }

        public static void addRoleForPanel (int role, int panel)
        {
            DateTime dateTime = DateTime.Now;
            SqlConnection connection = ConnectionMenager.GetConnection();

            string sql = @"INSERT INTO tbr_PanelRoles (idPanel, idRole) VALUES (@panelP,@roleP)";
            SqlCommand command = new SqlCommand(sql, connection);

            command.Parameters.AddWithValue("@roleP", role);
            command.Parameters.AddWithValue("@panelP", panel);

            command.ExecuteNonQuery();
            connection.Close();
        }

        public static int AuthenticateUserWithPanel(string panelName, int userID)
        {
            SqlConnection connection = ConnectionMenager.GetConnection();

            string sql = @"SELECT Panels.idPanel FROM tbr_PanelRoles INNER JOIN Panels on tbr_PanelRoles.idPanel = Panels.idPanel WHERE Panels.name = @panelNameP AND idRole = @userP";

            SqlCommand command = new SqlCommand(sql, connection);
            command.CommandType = CommandType.Text;

            command.Parameters.AddWithValue("@panelNameP", panelName);
            command.Parameters.AddWithValue("@userP", userID);

            SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleResult);

            int temp;
            reader.Read();
            try
            {
                temp = int.Parse(reader[0].ToString());
            }
            catch (Exception)
            {
                temp = 0;
            }

            connection.Close();
            return temp;
        }

    }
}

